/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.abc.cheque.ui.form;

import java.util.LinkedHashMap;
import java.util.Set;
import javafx.scene.control.ChoiceBox;
import javafx.util.StringConverter;

/**
 *
 * @author sencaki
 */
public class ChoiceBoxControl<T> extends BaseControl<T, ChoiceBox<T>> {

    private LinkedHashMap<String, T> itemMap = new LinkedHashMap<>();
    private LabelConverter lblConverter = new LabelConverter();
    private ChoiceBox<T> choicebox;
    public ChoiceBoxControl() {
        super(new ChoiceBox<T>());
        choicebox = getInputComponent();
        choicebox.setConverter(lblConverter);
    }

    private String getLabel(T object) {
        Set<String> keys = itemMap.keySet();
        for (String label : keys) {
            T obj = (T) itemMap.get(label);
            if (obj.equals(object)) {
                return label;
            }
        }
        return null;
    }

    @Override
    public void setValue(T value) {
        for (T item : choicebox.getItems()) {
            if (item.equals(value)) {
                choicebox.getSelectionModel().select(item);
                break;
            }
        }
    }

    @Override
    protected void bindValuePropertyWithControl(ChoiceBox<T> inputControl) {
        value.bind(inputControl.valueProperty());
    }

    public class LabelConverter extends StringConverter<T> {

        @Override
        public String toString(T value) {
            return getLabel((T) value);
        }

        @Override
        public T fromString(String value) {
            return itemMap.get(value);
        }
    }

    public void addItem(String label, T value) {
        itemMap.put(label, value);
        choicebox.getItems().add(value);
    }
}
